﻿using log4net;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RabbitMQDemo.Models
{
    public class RunRabbitMQ : BackgroundService
    {
        private ILog log;
        public RunRabbitMQ()
        {
            this.log = LogManager.GetLogger(Startup.repository.Name, typeof(RunRabbitMQ));
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //while (!stoppingToken.IsCancellationRequested)
            //{
            //    await Task.Delay(5000, stoppingToken);
            //}

        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            GetMsg();
            return Task.CompletedTask;
        }

        private void GetMsg()
        {
            //连接配置(类似连接字符串)
            ConnectionFactory rabbitFactory = new ConnectionFactory()
            {
                HostName = "127.0.0.1",
                UserName = "guest",
                Password = "guest",
                Port = 5672
            };

            //打开连接
            using (IConnection conn = rabbitFactory.CreateConnection())
            {
                //获取一个通道
                using (IModel channel = conn.CreateModel())
                {
                    //声明一个队列
                    channel.QueueDeclare("glzdemo1", false, false, false, null);

                    //获取客户端的关联
                    EventingBasicConsumer custom = new EventingBasicConsumer(channel);

                    //绑定一个接收事件(及时接收消息)
                    custom.Received += (x, ea) =>
                    {
                        var msgBody = ea.Body;
                        string msg = Encoding.UTF8.GetString(msgBody.ToArray());
                        log.Info(msg);
                        //返回消息确认
                        channel.BasicAck(ea.DeliveryTag, false);
                    }; //Custom_Received;

                    //开始接收消息(自动应答为false,获取消息后不会自动删除,自己控制消息是否删除)
                    channel.BasicConsume(queue: "glzdemo1", consumer: custom);

                    //Console.WriteLine("按任意值，退出程序");
                    //Console.ReadKey();
                }
            }

        }

        private void Custom_Received(object sender, BasicDeliverEventArgs e)
        {
            var msgBody = e.Body;
            string msg = Encoding.UTF8.GetString(msgBody.ToArray());
            log.Info(msg);

        }
    }
}
